package com.auto.survey

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.auto.survey.MainActivity.Companion.KEY_MENU_IMAGE
import com.auto.survey.MainActivity.Companion.KEY_MENU_TITLE

class MainAdapter: Adapter<MainAdapter.MainViewHodler>() {

    private var mlistener:OnItemClickListener?=null

    private val mData: MutableList<Map<String, Any>> = ArrayList();

    fun setDatas(data:List<Map<String, Any>>) {
        mData.clear()
        mData.addAll(data)
        notifyDataSetChanged();
    }

    fun setOnItemClickListener(listener:OnItemClickListener) {
        mlistener = listener
    }

    override fun getItemCount(): Int {
        if (mData.size > 0) {
            return mData.size;
        }

        return 0;
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHodler {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.adapter_menu, parent, false);
        return MainViewHodler(view)
    }

    override fun onBindViewHolder(holder: MainViewHodler, position: Int) {
        holder.imag.setImageResource(mData[position][KEY_MENU_IMAGE] as Int)
        holder.text.text = mData[position][KEY_MENU_TITLE] as String
        holder.parent.setOnClickListener {
            mlistener?.onItemClick(position, mData[position])
        }
    }

    inner class MainViewHodler(itemView: View) : ViewHolder(itemView) {
        val imag = itemView.findViewById<ImageView>(R.id.iv_grid_menu)
        val text = itemView.findViewById<TextView>(R.id.tv_grid_menu)
        val parent = itemView.findViewById<ConstraintLayout>(R.id.cl_grid_menu)
    }

    interface OnItemClickListener{
        fun onItemClick(position:Int, map:Map<String, Any>)
    }
}